package com.yogi.webframework.dao;

import java.io.Serializable;
import java.lang.reflect.ParameterizedType;
import java.util.List;

import org.apache.commons.lang.math.NumberUtils;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

public class GenericDaoHibernateImpl<T, ID extends Serializable> extends
		HibernateDaoSupport implements GenericDao<T, Serializable> {

	@SuppressWarnings("unchecked")
	public Class domainClass;

	@SuppressWarnings("unchecked")
	public GenericDaoHibernateImpl() {
		this.domainClass = (Class) ((ParameterizedType) getClass()
				.getGenericSuperclass()).getActualTypeArguments()[0];
	}

	@SuppressWarnings("unchecked")
	public Integer count() {
		List<T> list = getHibernateTemplate().find(
				"select count(*) from " + domainClass.getName() + " x");
		Integer count = NumberUtils.toInt(list.get(0).toString());
		return count;
	}

	public void delete(T domain) {
		getHibernateTemplate().delete(domain);
	}

	@SuppressWarnings("unchecked")
	public List<T> findAll() {
		return getHibernateTemplate().find("from " + domainClass.getName());
	}

	@SuppressWarnings("unchecked")
	public T findById(Serializable id) {
		final T domain = (T) getHibernateTemplate().load(domainClass, id);
		getHibernateTemplate().initialize(domain);
		return domain;
	}

	public void save(T domain) {
		getHibernateTemplate().saveOrUpdate(domain);
	}

}
